#include <glib.h>

typedef struct mydata_tag {
  int id;
  char *name;
}my_data_t;

void my_struct_free_func(gpointer data)
{
    my_data_t *mydata = NULL;
    mydata = (my_data_t *)data;

    if(NULL != mydata->name) {
        //g_print("free mydata->name: %s \n", mydata->name);
        free(mydata->name);
    }

    return;
}

void my_struct_printf(gpointer data, gpointer user_data)
{
    g_print("%s: id=%d, name=%s, user_data=%s\n", __FUNCTION__, 
        ((my_data_t *)data)->id, ((my_data_t *)data)->name, (char *)user_data);
}

static gint _slist_position_custom(GSList *list, GSList *llink)
{
    gint i = 0;

    while (list) {
        if (((my_data_t *)(list->data))->id == ((my_data_t *)(llink->data))->id)
        return i;
        i++;
        list = list->next;
    }

    return -1;
}

static void test_slist_find_custom_func(void)
{
    gint i = 0;
    GSList *slist = NULL;
    GSList *slink = NULL;
    my_data_t *snode = NULL;
    my_data_t mydata[16];
    gint pos = 0;
    my_data_t pos_node = {0, NULL};
    GSList pos_link = {NULL, NULL};
    char name[16] = {0};

    memset(mydata, 0, sizeof(my_data_t)*5);
    for(i=0;i<5;i++) {
        mydata[i].id = i;
        g_snprintf(name, 16, "data is %d", i);
        mydata[i].name = strdup(name);
        slist = g_slist_append(slist,  (gpointer)&mydata[i]);
    }

    g_print("\n");
    g_print("len=%d \n", g_slist_length(slist));
    g_slist_foreach(slist, my_struct_printf, "my_struct_printf");

    pos_node.id = 3;
    pos_node.name = strdup("data is 3");
    pos_link.data = &pos_node;
    pos_link.next = NULL;
    pos = _slist_position_custom(slist, &pos_link);
    g_print("pos=%d \n", pos);
    free(pos_node.name);

    g_slist_free_full(slist, my_struct_free_func);
}

gint main (gint argc, gchar *argv[])
{
    g_test_init (&argc, &argv, NULL);

    g_test_add_func ("/slist/find_custom_func", test_slist_find_custom_func);

    return g_test_run ();
}